/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.CustomerMgtBackend.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.LinkedList;

/**
 *
 * @author Thomas
 */
public class DB_ConnectionPool implements DB_Config {

    private LinkedList<Connection> connections = new LinkedList<Connection>();
    private final int MAXCON = 150;
    private int numCon = 0;
    private static DB_ConnectionPool theInstance;
    

    private DB_ConnectionPool() throws ClassNotFoundException{
			Class.forName(DB_DRIVER);
    }

    public synchronized Connection getConnection() throws Exception {
        System.out.println(numCon);
        if (connections.isEmpty()) {
            if (connections.size() == MAXCON) {
                throw new Exception("Connection-Limit reached!");
            }
            Connection con = DriverManager.getConnection((DB_URL+DB_NAME),DB_USER,DB_PASSWD);
            numCon++;
            return con;
        }else{
            return connections.poll();
        }
    }

    public synchronized void releaseConnection(Connection con){
        connections.offer(con);
    }
    
    public static DB_ConnectionPool getInstance() throws ClassNotFoundException {
        if (theInstance == null) {
            theInstance = new DB_ConnectionPool();
        }
        return theInstance;
    }
}
